package com.tanhua.sso.service;

import com.tanhua.sso.config.AliyunConfig;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service
public class PicUploadService {
    @Autowired
    AliyunConfig aliyunConfig;

    //判断上传的图片格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};


    public PicUploadResult upload(MultipartFile uploadFile) {

        PicUploadResult picUploadResult=new PicUploadResult();
        //图片做校验，对后缀名
        boolean isLegal=false;
        for (String type : IMAGE_TYPE) {
            //如果传进来的uploadFile的文件名，是以上述的后缀名结尾的，就返回true
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),type)){
                isLegal=true;
                break;
            }
        }
        //图片不符合
        if (!isLegal){
            picUploadResult.setStatus("error");
            return picUploadResult;
        }

        //设置新图片的路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        //上传图片
        try {
            aliyunConfig.oSSClient().putObject(aliyunConfig.getBucketName(),filePath,
                    new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            picUploadResult.setStatus("error");
            return picUploadResult;
        }
        // 上传成功
        picUploadResult.setStatus("done");
        picUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        picUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        //上传成功
        return picUploadResult;
    }

    private String getFilePath(String fileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(fileName, ".");
    }

}
